package cn.itsource.service;

import cn.hutool.http.HttpUtil;
import cn.itsource.config.WeChatProperties;
import cn.itsource.onstants.Constants;
import cn.itsource.pojo.dto.RegisterDto;
import cn.itsource.pojo.dto.UserPhoneAccessToKen;
import cn.itsource.pojo.dto.UserPhoneDto;
import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Data
@NoArgsConstructor
@AllArgsConstructor
public class WeChatService {
    private WeChatProperties weChatProperties;

    public RegisterDto getWeChatOpenId(String code){
        //拼接请求地址
        String sendUrl = String.format(Constants.CODE_2_SESSION_URL, weChatProperties.getAppid(),
                weChatProperties.getAppSecret(), code);
        log.info(sendUrl);//打印日志 只要打印核心
        //发送请求
        String result =  HttpUtil.get(sendUrl);//返回的是 JSON字符串
        //将json字符串转为对象
       return JSONObject.parseObject(result, RegisterDto.class);
    }

    public String getUserPhone(String phoneCode){
        //获取access_token
        String sendAccessToken = String.format(Constants.USER_PHONE_ACCESS_TOKEN, weChatProperties.getAppid(), weChatProperties.getAppSecret());
        String result =  HttpUtil.get(sendAccessToken);//返回的是 JSON字符串
        UserPhoneAccessToKen userPhoneAccessToKen = JSONObject.parseObject(result, UserPhoneAccessToKen.class);
        String accessToken = userPhoneAccessToKen.getAccess_token();
        //获取手机号
        String sendGetUserPhone = String.format(Constants.USER_PHONE, accessToken);
        Map<String,Object> map = new HashMap(1);
        map.put("code",phoneCode);
        String userPhone = HttpUtil.post(sendGetUserPhone, map);
        //方式一
//        UserPhoneDto userPhoneDto = JSONObject.parseObject(userPhone, UserPhoneDto.class);
//        return userPhoneDto.getPhone_info().getPhoneNumber();
        //方式二
        JSONObject jsonObject = JSONObject.parseObject(userPhone);
        JSONObject phoneInfo = (JSONObject)jsonObject.get("phone_info");
        Object phoneNumber = phoneInfo.get("phoneNumber");
        return phoneNumber.toString();
    }
}
